import numpy as np
import cv2
import matplotlib.pyplot as plt

def sobel_filter(image):
    # Sobel算子
    sobel_x = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
    sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

    # 使用cv2.filter2D进行卷积操作
    grad_x = cv2.filter2D(image, cv2.CV_32F, sobel_x)
    grad_y = cv2.filter2D(image, cv2.CV_32F, sobel_y)

    # 计算梯度幅值
    grad_magnitude = np.sqrt(grad_x ** 2 + grad_y ** 2)
    grad_magnitude = np.clip(grad_magnitude, 0, 255).astype(np.uint8)

    return grad_magnitude

def custom_convolution(image, kernel):
    # 获取卷积核尺寸
    kernel_size = kernel.shape[0]
    pad_size = kernel_size // 2

    # 填充图像
    padded_image = np.pad(image, pad_size, mode='reflect')

    # 初始化输出图像
    output_image = np.zeros_like(image, dtype=np.float32)

    # 使用矢量化操作进行卷积
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            region = padded_image[i:i + kernel_size, j:j + kernel_size]
            output_image[i, j] = np.sum(region * kernel)

    output_image = np.clip(output_image, 0, 255).astype(np.uint8)
    return output_image

def compute_color_histogram(image):
    # 分离颜色通道
    channels = ['b', 'g', 'r']
    histograms = []

    for i, color in enumerate(channels):
        hist = cv2.calcHist([image], [i], None, [256], [0, 256])
        histograms.append(hist)

    return histograms

def visualize_histogram(histograms):
    colors = ['blue', 'green', 'red']
    plt.figure()
    for i, hist in enumerate(histograms):
        plt.bar(range(256), hist[:, 0], color=colors[i], alpha=0.5, label=f'{colors[i]} channel')
    plt.title('Color Histogram')
    plt.xlabel('Pixel Value')
    plt.ylabel('Frequency')
    plt.legend()
    plt.show()

def extract_texture_features(image):
    # 简单的纹理特征提取（例如：灰度共生矩阵）
    glcm = np.zeros((256, 256), dtype=np.float32)
    for i in range(image.shape[0] - 1):
        for j in range(image.shape[1] - 1):
            glcm[image[i, j], image[i + 1, j + 1]] += 1
    glcm /= glcm.sum()
    return glcm

# 主程序
if __name__ == "__main__":
    # 读取图像
    image_path = 'image.jpg'  # 替换为你自己的图像路径
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # Sobel滤波
    sobel_filtered_image = sobel_filter(image)
    cv2.imwrite('sobel_filtered_image1.jpg', sobel_filtered_image)

    # 自定义卷积核滤波
    kernel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
    custom_filtered_image = custom_convolution(image, kernel)
    cv2.imwrite('custom_filtered_image1.jpg', custom_filtered_image)

    # 计算颜色直方图并可视化
    color_histograms = compute_color_histogram(cv2.imread(image_path))
    visualize_histogram(color_histograms)

    # 提取纹理特征并保存为npy文件
    texture_features = extract_texture_features(image)
    np.save('texture_features1.npy', texture_features)
